package jprint.jfx.http;

import java.io.ByteArrayInputStream;
import javax.annotation.Nonnull;
import jprint.base.AppContext;
import jprint.base.http.AbstractRequestHandler;
import jprint.base.http.Http;
import jprint.base.label.FontService;
import jprint.base.util.JsonUtil;
import jprint.base.util.Strings;

/**
 * @author zw-zheng
 * Created on 2021-02-04
 */
class FontHandler extends AbstractRequestHandler {

    private final FontService fontService;

    FontHandler(@Nonnull AppContext appContext) {
        fontService = FontService.getInstance(appContext);
    }

    @Override public boolean handle(Http.HttpRequest request, Http.HttpResponse response) {
        if (request.uri().startsWith("/api/font") && request.method() == Http.Method.GET) {
            response.setContentType(JSON_MIME_TYPE)
                .setStatus(200)
                .write(JsonUtil.toJsonString(fontService.fontList()), Strings.UTF_8);
            return true;
        }

        if (request.uri().equals("/api/text-to-image")) {
            byte[] imageBytes = fontService.drawTextAsImage(request.parameters());
            response.setContentType(contentTypeOf("dummy.png"))
                .setStatus(200)
                .write(new ByteArrayInputStream(imageBytes));
            return true;
        }

        return false;
    }
}
